<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/djean/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/djean/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/djean/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/djean/images/logo.svg" color="#222">

<link rel="stylesheet" href="/djean/css/main.css">


<link rel="stylesheet" href="/djean/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/djean/',
    scheme: 'Pisces',
    version: '7.5.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="代理模式 在生活中可以找到很多代理模式的场景，比如明星的经纪人就是一个典型的例子，如某商业演出需要请一个大明星，只能是先去联系这个明星的经纪人，而不是直接去联系这个明星。由经纪人代理明星出面，商量好演出的细节和酬劳。 保护代理和虚拟代理如果明星不想接某些商业演出的话，或者商业演出给出的酬劳没有达到这位大明星的入门要求，则这个请求就直接在经纪人这一关就过滤掉了，这种代理叫做保护代理。保护代理用于控制">
<meta name="keywords" content="JavaScript">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript设计模式之代理模式">
<meta property="og:url" content="https:&#x2F;&#x2F;djiangogo.gitee.io&#x2F;2019&#x2F;11&#x2F;25&#x2F;proxy-pattern&#x2F;index.html">
<meta property="og:site_name" content="djean的个人博客">
<meta property="og:description" content="代理模式 在生活中可以找到很多代理模式的场景，比如明星的经纪人就是一个典型的例子，如某商业演出需要请一个大明星，只能是先去联系这个明星的经纪人，而不是直接去联系这个明星。由经纪人代理明星出面，商量好演出的细节和酬劳。 保护代理和虚拟代理如果明星不想接某些商业演出的话，或者商业演出给出的酬劳没有达到这位大明星的入门要求，则这个请求就直接在经纪人这一关就过滤掉了，这种代理叫做保护代理。保护代理用于控制">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-11-26T11:33:01.695Z">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://djiangogo.gitee.io/2019/11/25/proxy-pattern/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>JavaScript设计模式之代理模式 | djean的个人博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/djean/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">djean的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/djean/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/djean/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/djean/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/djean/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/djean/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://djiangogo.gitee.io/djean/2019/11/25/proxy-pattern/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/djean/images/avatar.png">
      <meta itemprop="name" content="djean">
      <meta itemprop="description" content="时刻保持一个上进心">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="djean的个人博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          JavaScript设计模式之代理模式
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-11-25 20:44:01" itemprop="dateCreated datePublished" datetime="2019-11-25T20:44:01+08:00">2019-11-25</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-11-26 19:33:01" itemprop="dateModified" datetime="2019-11-26T19:33:01+08:00">2019-11-26</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/djean/categories/javascript%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" itemprop="url" rel="index">
                    <span itemprop="name">javascript设计模式</span>
                  </a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="代理模式"><a href="#代理模式" class="headerlink" title="代理模式"></a>代理模式</h3><p> 在生活中可以找到很多代理模式的场景，比如明星的经纪人就是一个典型的例子，如某商业演出需要请一个大明星，只能是先去联系这个明星的经纪人，而不是直接去联系这个明星。由经纪人代理明星出面，商量好演出的细节和酬劳。</p>
<h3 id="保护代理和虚拟代理"><a href="#保护代理和虚拟代理" class="headerlink" title="保护代理和虚拟代理"></a>保护代理和虚拟代理</h3><p>如果明星不想接某些商业演出的话，或者商业演出给出的酬劳没有达到这位大明星的入门要求，则这个请求就直接在经纪人这一关就过滤掉了，这种代理叫做保护代理。保护代理用于控制不同权限的对象对目标对象的访问，但是JavaScript并不容易实现保护代理，因为我们无法判断谁访问了某个对象。虚拟代理则是一种最常用的代理模式<br>虚拟代理指的是把一些开销很大的对象，延迟到真正需要它的时候才去创建，比如上面说的，如果在程序界，演出主办方和明星商谈演出细节是一个很大的开销，这个时候经纪人就会选择在明星心情好的时候去约好双方洽谈，这样成功的机率也很大。</p>
<h3 id="虚拟代理实现图片预加载"><a href="#虚拟代理实现图片预加载" class="headerlink" title="虚拟代理实现图片预加载"></a>虚拟代理实现图片预加载</h3><p>在Web开发中，图片预加载技术是一种常用的技术，如果直接给某个img标签节点设置src属性，由于图片过大或者网络不佳，图片的位置往往会有一段时间的空白，这个对体验相当不友好。常见的做法是先用一张loading图片占位，然后用异步加载的方式加载图片，等图片加载好了之后再把它填充到img节点，这种情况就很适合使用虚拟代理了。<br>下面用代码来实现这个虚拟代理，首先创建本体对象，这个对象负责往页面中创建一个img标签，并且提供一个对外的接口setSrc，外界调用这个api，便可以给该img标签设置src属性</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> MyImage = (<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> imgNode = <span class="built_in">document</span>.createElement(<span class="string">'img'</span>);</span><br><span class="line">    <span class="built_in">document</span>.body.appendChild(imgNode);</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        setSrc: <span class="function"><span class="keyword">function</span> (<span class="params">src</span>) </span>&#123;</span><br><span class="line">            imgNode.src = src;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>
<p>我们在控制台把网速调慢至5KB/s，然后再通过MyImage.setSrc给该img节点设置src属性，可以看到，再图片被加载好之前，页面中有一段很长的空白时间。这个是不被接受的。<br>现在开始引入代理对象proxyImage对象，通过这个对象，在图片被真正加载好之前，在页面中将出现一张占位的loading图，用来给用户友好的提示。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> myImage = (<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> imgNode = <span class="built_in">document</span>.createElement(<span class="string">'img'</span>);</span><br><span class="line">    <span class="built_in">document</span>.body.appendChild(imgNode);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        setSrc: <span class="function"><span class="keyword">function</span> (<span class="params">src</span>) </span>&#123;</span><br><span class="line">            imgNode.src = src;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)()</span><br><span class="line"><span class="keyword">var</span> proxyImage = (<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> img = <span class="keyword">new</span> Image;</span><br><span class="line">    img.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        myImage.setSrc(<span class="keyword">this</span>.src);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        setSrc: <span class="function"><span class="keyword">function</span> (<span class="params">src</span>) </span>&#123;</span><br><span class="line">            myImage.setSrc(<span class="string">'本地的一张菊花图路径'</span>);</span><br><span class="line">            img.src = src;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)()</span><br><span class="line"><span class="comment">// 使用</span></span><br><span class="line">proxyImage.setSrc(<span class="string">'需要加载的图片路径'</span>);</span><br></pre></td></tr></table></figure>
<p>我们通过proxyImage间接的访问myImage，当我们调用proxyImage对象的setSrc接口时候，首先会把img的src属性设置成本地的一张loading图，然后就把proxyImage中的img的src设置成我们需要加载的真正的图片url，再使用onload来监听这个图片的是否加载完成。等到加载完成后，就把img的src设置成真正的src。</p>
<h3 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h3><p>虽然代理模式很有用，但是我们在编写业务代码的时候，往往不需要去预先猜测是否需要使用代理模式，当我们发现不方便直接访问某个对象的时候，再来写代理也不迟。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/djean/tags/JavaScript/" rel="tag"># JavaScript</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
                <a href="/djean/2019/11/24/singleton-pattern/" rel="next" title="JavaScript设计模式之单例模式">
                  <i class="fa fa-chevron-left"></i> JavaScript设计模式之单例模式
                </a>
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
            </div>
          </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#代理模式"><span class="nav-number">1.</span> <span class="nav-text">代理模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#保护代理和虚拟代理"><span class="nav-number">2.</span> <span class="nav-text">保护代理和虚拟代理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#虚拟代理实现图片预加载"><span class="nav-number">3.</span> <span class="nav-text">虚拟代理实现图片预加载</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#小结"><span class="nav-number">4.</span> <span class="nav-text">小结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <img class="site-author-image" itemprop="image" alt="djean"
    src="/djean/images/avatar.png">
  <p class="site-author-name" itemprop="name">djean</p>
  <div class="site-description" itemprop="description">时刻保持一个上进心</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/djean/archives/">
        
          <span class="site-state-item-count">2</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/djean/categories/">
          
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/djean/tags/">
          
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">djean</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.0.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.5.0
  </div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/djean/lib/anime.min.js"></script>
  <script src="/djean/lib/velocity/velocity.min.js"></script>
  <script src="/djean/lib/velocity/velocity.ui.min.js"></script>
<script src="/djean/js/utils.js"></script><script src="/djean/js/motion.js"></script>
<script src="/djean/js/schemes/pisces.js"></script>
<script src="/djean/js/next-boot.js"></script>



  
















  

  

</body>
</html>
